#include <asm-generic/errno-base.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgbuf {
  long mtype;      /* message type, must be > 0 */
  char mtext[100]; /* message data */
};
void *rev(void *);
void *sen(void *);

int main(int argc, char *argv[]) {

  pthread_t tid;
  pthread_t tid2;

  pthread_create(&tid, NULL, sen, NULL);
  pthread_create(&tid2, NULL, rev, NULL);

  pthread_join(tid, NULL);
  pthread_join(tid2, NULL);

  pthread_exit(NULL);
}

void *rev(void *argv) {
  key_t key = ftok(".", 1);
  if (key < 0) {
    perror("ftok fail");
    exit(-1);
  }
  int msg_id = msgget(key, IPC_CREAT | IPC_EXCL | 0666);
  if (msg_id < 0 && errno == EEXIST) {
    msg_id = msgget(key, 0666);
  }
  printf("p2 msg id = %d\n",msg_id);

  struct msgbuf buf;

  while (1) {
    msgrcv(msg_id, &buf, sizeof(buf), 2, 0);
    printf("read is %s\n", buf.mtext);
    if (!strcmp("bye", buf.mtext))
      break;
  }

  pthread_exit(NULL);
}
void *sen(void *argv) {
  key_t key = ftok(".", 1);
  if (key < 0) {
    perror("ftok fail");
    exit(-1);
  }
  int msg_id = msgget(key, IPC_CREAT | IPC_EXCL | 0666);
  if (msg_id < 0 && errno == EEXIST) {
    msg_id = msgget(key, 0666);
  }
  
  struct msgbuf buf;
  buf.mtype = 1;

  while (1) {
    scanf("%s", buf.mtext);
    msgsnd(msg_id, &buf, sizeof(buf), 0);
    if (!strcmp("bye", buf.mtext))
      break;
  }

  pthread_exit(NULL);
}


